package com.erdos.hyt.mall.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Order(2)
@Configuration
@MapperScan(basePackages = { "com.erdos.hyt.*.mapper" }, sqlSessionFactoryRef = "sqlSessionFactory")
public class MyBatisConfig {

	@Resource(name = "defualtDataSource")
	DataSource ds;
	
	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(ds);
		bean.setTypeAliasesPackage("com.erdos.hyt.mall.model,com.erdos.hyt.users.model,com.erdos.hyt.common.model,com.erdos.hyt.order.model");
		PathMatchingResourcePatternResolver mybatisConfigResolver = new PathMatchingResourcePatternResolver();
		bean.setConfigLocation(mybatisConfigResolver.getResource("classpath:/mybatis-config.xml"));
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		bean.setMapperLocations(resolver.getResources("classpath*:/mapping/*.xml"));
		bean.setTypeHandlersPackage("com.github.javaplugs.mybatis");
		return bean;
	}

	@Bean
	public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
